/*
 * isa_dma.c
 *
 * Copyright (C) 2013 Aleksandar Andrejevic <theflash@sdf.lonestar.org>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <isa_dma.h>
#include <lock.h>

static dword_t isa_dma_bitmap[1 + ((ISA_DMA_MEM_BLOCKS - 1) / 32)] = { 0 };
static DECLARE_LOCK(dma_lock);

void *isa_dma_alloc(void)
{
    dword_t i;

    for (i = 0; i < ISA_DMA_MEM_BLOCKS; i++) if (!test_bit(isa_dma_bitmap, i))
    {
        set_bit(isa_dma_bitmap, i);
        return (void*)(ISA_DMA_MEM_START + (i * ISA_DMA_MEM_ALIGNMENT));
    }

    return NULL;
}

void isa_dma_free(void *dma_buffer)
{
    clear_bit(isa_dma_bitmap, ((dword_t)dma_buffer - ISA_DMA_MEM_START) / ISA_DMA_MEM_ALIGNMENT);
}

void isa_dma_read(dword_t channel, void *buffer, word_t count)
{
    channel &= 7;
    if (count == 0) return;
    else count--;

    lock_acquire(&dma_lock);
    outportb(ISA_DMA_SINGLE_MASK_REG(channel), ISA_DMA_MASK_ON | (channel & 3));

    outportb(ISA_DMA_FF_RESET_REG(channel), 0xFF);
    outportb(ISA_DMA_SAR(channel), (dword_t)buffer & 0xFF);
    outportb(ISA_DMA_SAR(channel), ((dword_t)buffer >> 8) & 0xFF);
    outportb(ISA_DMA_PAR(channel), ((dword_t)buffer >> 16) & 0xFF);

    outportb(ISA_DMA_FF_RESET_REG(channel), 0xFF);
    outportb(ISA_DMA_CNT(channel), count & 0xFF);
    outportb(ISA_DMA_CNT(channel), count >> 8);

    outportb(ISA_DMA_MODE_REG(channel), 0x48 | (channel & 3));

    outportb(ISA_DMA_SINGLE_MASK_REG(channel), (channel & 3));
    lock_release(&dma_lock);
}

void isa_dma_write(dword_t channel, void *buffer, dword_t count)
{
    channel &= 7;
    if (count == 0) return;
    else count--;

    lock_acquire(&dma_lock);
    outportb(ISA_DMA_SINGLE_MASK_REG(channel), ISA_DMA_MASK_ON | (channel & 3));

    outportb(ISA_DMA_FF_RESET_REG(channel), 0xFF);
    outportb(ISA_DMA_SAR(channel), (dword_t)buffer & 0xFF);
    outportb(ISA_DMA_SAR(channel), ((dword_t)buffer >> 8) & 0xFF);
    outportb(ISA_DMA_PAR(channel), ((dword_t)buffer >> 16) & 0xFF);

    outportb(ISA_DMA_FF_RESET_REG(channel), 0xFF);
    outportb(ISA_DMA_CNT(channel), count & 0xFF);
    outportb(ISA_DMA_CNT(channel), count >> 8);

    outportb(ISA_DMA_MODE_REG(channel), 0x44 | (channel & 3));

    outportb(ISA_DMA_SINGLE_MASK_REG(channel), (channel & 3));
    lock_release(&dma_lock);
}
